#pragma once
#include <QObject>
#include <QtSql/QSqlDatabase>
#include <QQueue>
#include <QMutex>
#include <QWaitCondition>
#include <QAtomicInt>
#include <QUuid>
#include <QDateTime>

class ConnectionPool : public QObject
{
    Q_OBJECT
public:
    enum DBType { SQLite, MySQL, MariaDB, PostgreSQL, Oracle, ODBC };

    explicit ConnectionPool(QObject* parent = nullptr);
    ~ConnectionPool();

    void initialize();
    QSqlDatabase getConnection(int retries = 3);
    void releaseConnection(QSqlDatabase conn);
    void cleanupSession(QSqlDatabase& conn);
    // 配置验证查询的公有接口
    void setValidationQuery(const QString& query);

    // 事务管理
    bool beginTransaction();
    bool commitTransaction();
    bool rollbackTransaction();

    // 状态监控
    int activeConnections() const;  // 确保存在此声明
    // 添加空闲连接数查询接口
    int idleConnections() const;
    int activeCount() const
    {
        return m_activeCount.loadAcquire();
    }
    int idleCount() const
    {
        QMutexLocker l( & m_mutex);
        return m_available.size();
    }
    QString driverName() const;
    QString getDefaultValidationQuery() const;

private:
    struct ConnInfo
    {
        QString name;
        QDateTime lastUsed;
        bool inTransaction = false;
    };
    QHash<QString, bool> m_transactionStatus;  // 事务状态跟踪
    mutable QMutex m_transactionMutex;         // 事务状态锁
    void loadConfig();
    QSqlDatabase createConnection();
    bool validateConnection(QSqlDatabase& conn);


    QQueue<ConnInfo> m_available;
    mutable QMutex m_mutex;
    QWaitCondition m_cond;
    QAtomicInt m_activeCount;

    // 配置参数
    DBType m_type;
    QString m_dbName;
    QString m_host;
    int m_port;
    QString m_user;
    QString m_password;
    int m_maxConn;
    QString m_validationQuery = "SELECT 1"; // 默认验证查询
    QMutex m_sqliteWriteLock;
};
